package com.tuanzi.loan.business.repository.application.impl;

import com.tuanzi.loan.business.repository.application.custom.LoanApplicationExportGroupRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.application.LoanApplicationExportGroupRequest;
import com.tuanzi.loan.vo.response.application.LoanApplicationExportGroupResponse;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import static com.tuanzi.loan.generated.jooq.loan.Tables.LOAN_APPLICATION_EXPORT_GROUP;
import static com.tuanzi.loan.generated.jooq.loan.Tables.LOAN_APPLICATION_EXPORT_GROUP_PAGE;

/**
 * @Auther: hequnayu
 * @Date: 2019/7/30 15:30
 * @Description:
 */
public class LoanApplicationExportGroupRepositoryImpl extends JOOQBaseRepository implements LoanApplicationExportGroupRepositoryCustom {

    @Override
    public Page<LoanApplicationExportGroupResponse> list(LoanApplicationExportGroupRequest searchRequest, Pageable pageable) {
        leftJoin(LOAN_APPLICATION_EXPORT_GROUP_PAGE,LOAN_APPLICATION_EXPORT_GROUP_PAGE.ID.eq(LOAN_APPLICATION_EXPORT_GROUP.PAGE_ID));
        eq(LOAN_APPLICATION_EXPORT_GROUP.PAGE_ID, searchRequest.getPageId());
        eq(LOAN_APPLICATION_EXPORT_GROUP.TYPE, searchRequest.getType());
        return search(pageable, new LoanBannerGroupSearchResponseRecordMapper());
    }

    @Override
    public Integer getBiggestGroupId() {
        Integer biggestGroupId = dslContext.fetchOne("SELECT MAX(GROUP_ID) AS groupId FROM loan_application_export_group").into(Integer.class);
        if(biggestGroupId == null){
            return 1;
        }
        return biggestGroupId + 1;
    }

    private final class LoanBannerGroupSearchResponseRecordMapper implements RecordMapper<Record, LoanApplicationExportGroupResponse> {

        @Override
        public LoanApplicationExportGroupResponse map(Record record) {
            LoanApplicationExportGroupResponse response = new LoanApplicationExportGroupResponse();
            response.setId(record.get(LOAN_APPLICATION_EXPORT_GROUP.ID));
            response.setName(record.get(LOAN_APPLICATION_EXPORT_GROUP.NAME));
            response.setPageName(record.get(LOAN_APPLICATION_EXPORT_GROUP_PAGE.NAME));
            response.setType(record.get(LOAN_APPLICATION_EXPORT_GROUP.TYPE));
            response.setGroupId(record.get(LOAN_APPLICATION_EXPORT_GROUP.GROUP_ID));
            return response;
        }
    }
    @Override
    protected TableImpl getTable() {
        return LOAN_APPLICATION_EXPORT_GROUP;
    }

}
